package com.itlong.cloud.controller.finance;

import com.itlong.cloud.POJO.DTO.property.PropertyArrearPeopleManageDTO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.property.PropertyArrearPeopleManageVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.abstracts.BaseController;
import com.itlong.cloud.annotation.AuthAccessRequired;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.enumerate.FileCatalogEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.PropertyErrorCodeEnum;
import com.itlong.cloud.paymenthub.IPropertyArrearPeopleManageServiceClient;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.utils.file.UploadFileUtil;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <desc>
 *      欠费人员管理控制器
 * <desc/>
 *
 * @createDate 2019/05/22
 */
@RestController
@RequestMapping("/propertyValue/arrearagePeopleManage")
@RefreshScope
public class PropertyArrearPeopleManageController extends BaseController {

    @Value("${" + PlatformConstants.FILE_FTP_HOST + "}")
    public String FILE_FTP_HOST;

    @Value("${" + PlatformConstants.FILE_FTP_PORT + "}")
    public String FILE_FTP_PORT;

    @Value("${" + PlatformConstants.FILE_FTP_USERNAME + "}")
    public String FILE_FTP_USERNAME;

    @Value("${" + PlatformConstants.FILE_FTP_PASSWORD + "}")
    public String FILE_FTP_PASSWORD;

    @Value("${" + PlatformConstants.FILE_ACCESS_URL + "}")
    public String FILE_ACCESS_URL;

    @Autowired
    private IPropertyArrearPeopleManageServiceClient iPropertyArrearPeopleManageServiceClient;


    /**
     * <desc>
     *      分页获取欠费人员管理信息
     * </desc>
     *
     * @param propertyArrearPeopleManageDTO 欠费人员管理DTO
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2019/05/22
     */
    @ResponseBody
    @AuthAccessRequired
    @PostMapping("getPage")
    public Object getPage(PropertyArrearPeopleManageDTO propertyArrearPeopleManageDTO) {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            propertyArrearPeopleManageDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyArrearPeopleManageDTO.class, request);
            if (propertyArrearPeopleManageDTO == null) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (StringUtils.isBlank(propertyArrearPeopleManageDTO.getProjectId())) {
                return new MessageVO(PropertyErrorCodeEnum.PUB_PROJECT_ID_EMPTY_ERR.getErrorCode());
            }
            String shareProfitType = iPropertyArrearPeopleManageServiceClient.getProjectProfitType(propertyArrearPeopleManageDTO.getProjectId());
            if (!"2".equals(shareProfitType)) {
                // 项目绑定的分润规则类型为限全部
                return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), (Object) "1");
            }
            Page<PropertyArrearPeopleManageVO> page = iPropertyArrearPeopleManageServiceClient.getPage(propertyArrearPeopleManageDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), page);
        } catch (Exception e) {
            throw new DataAccessException("【物业-物业增值】分页获取欠费人员管理信息失败", e);
        }
    }

    /**
     * <desc>
     *      欠费人员管理添加地址
     * </desc>
     *
     * @param propertyArrearPeopleManageDTO 欠费人员管理DTO
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2019/05/22
     */
    @ResponseBody
    @PostMapping("save")
    @AuthAccessRequired
    @LoggerInfo(operateDesc = LogDescConstant.ARREAR_PEOPLE_ADDRESS_ADD_LOG_DESC)
    public Object save(PropertyArrearPeopleManageDTO propertyArrearPeopleManageDTO){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            propertyArrearPeopleManageDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyArrearPeopleManageDTO.class, request);
            if (propertyArrearPeopleManageDTO == null || StringUtils.isBlank(propertyArrearPeopleManageDTO.getBuildId()) || StringUtils.isBlank(propertyArrearPeopleManageDTO.getUnitId())
                    || StringUtils.isBlank(propertyArrearPeopleManageDTO.getRoomId())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (StringUtils.isBlank(propertyArrearPeopleManageDTO.getProjectId())) {
                return new MessageVO(PropertyErrorCodeEnum.PUB_PROJECT_ID_EMPTY_ERR.getErrorCode());
            }
            Page<PropertyArrearPeopleManageVO> page = iPropertyArrearPeopleManageServiceClient.getPage(propertyArrearPeopleManageDTO);
            if (page.getRows() != null && !page.getRows().isEmpty()) {
                return new MessageVO(PropertyErrorCodeEnum.ARREARAGE_ROOM_EXIST_ERR.getErrorCode());
            }
            iPropertyArrearPeopleManageServiceClient.save(propertyArrearPeopleManageDTO);
            return new MessageVO(propertyArrearPeopleManageDTO.getRoomId(), BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【物业-物业增值】欠费人员管理添加地址失败", e);
        }
    }

    /**
     * <desc>
     *      导出欠费人员管理表单
     * </desc>
     *
     * @param propertyArrearPeopleManageDTO 欠费人员管理DTO
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2019/05/22
     */
    @ResponseBody
    @AuthAccessRequired
    @PostMapping("export")
    public Object export(PropertyArrearPeopleManageDTO propertyArrearPeopleManageDTO){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            propertyArrearPeopleManageDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyArrearPeopleManageDTO.class, request);
            if (propertyArrearPeopleManageDTO == null) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (StringUtils.isBlank(propertyArrearPeopleManageDTO.getProjectId())) {
                return new MessageVO(PropertyErrorCodeEnum.PUB_PROJECT_ID_EMPTY_ERR.getErrorCode());
            }
            List<PropertyArrearPeopleManageVO> propertyArrearPeopleManageVOList = iPropertyArrearPeopleManageServiceClient.getExportData(propertyArrearPeopleManageDTO);
            if (propertyArrearPeopleManageVOList == null || propertyArrearPeopleManageVOList.isEmpty()) {
                return new MessageVO(PropertyErrorCodeEnum.EXPORT_DATA_EMPTY_ERR.getErrorCode());
            }
            if (propertyArrearPeopleManageVOList.size() > 2000) {
                return new MessageVO(PropertyErrorCodeEnum.EXPORT_DATA_TOO_MANY_ERR.getErrorCode());
            }
            String[] title = {"序号","住户名称","地址","手机号","添加时间","操作人"};
            short rowHeight = 420;
            //创建excel工作簿
            HSSFWorkbook workbook = new HSSFWorkbook();
            //创建工作表sheet并设置简单格式
            HSSFSheet sheet = workbook.createSheet();
            sheet.setDefaultColumnWidth(16);
            //创建第一行
            HSSFRow row = sheet.createRow(0);
            row.setHeight(rowHeight);
            HSSFCell cell = null;
            //插入第一行数据的表头
            for (int i = 0; i < title.length; i++) {
                cell = row.createCell(i);
                cell.setCellValue(title[i]);
            }
            //写入数据
            for (int carIndex = 0; carIndex < propertyArrearPeopleManageVOList.size(); carIndex++) {
                PropertyArrearPeopleManageVO propertyArrearPeopleManageVO = propertyArrearPeopleManageVOList.get(carIndex);
                int rowIndex = carIndex + 1; // 第一行已为标题行
                HSSFRow dataRow = sheet.createRow(rowIndex);
                dataRow.setHeight(rowHeight);
                HSSFCell noteCell = dataRow.createCell(0);
                noteCell.setCellValue(rowIndex);
                noteCell = dataRow.createCell(1);
                noteCell.setCellValue(propertyArrearPeopleManageVO.getRealName());
                noteCell = dataRow.createCell(2);
                noteCell.setCellValue(propertyArrearPeopleManageVO.getAddress());
                noteCell = dataRow.createCell(3);
                noteCell.setCellValue(propertyArrearPeopleManageVO.getPhoneNum());
                noteCell = dataRow.createCell(4);
                noteCell.setCellValue(propertyArrearPeopleManageVO.getCreateTime());
                noteCell = dataRow.createCell(5);
                noteCell.setCellValue(propertyArrearPeopleManageVO.getOperateName());
            }
            String fileName = String.format("%s_arrearagePeopleManage_%s.xls",
                    propertyArrearPeopleManageDTO.getProjectId(),
                    DateFormatUtils.format(new Date(), "yyyyMMddHHmmssSSS"));
            fileName = URLEncoder.encode(fileName, "UTF-8");
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            workbook.write(os);
            byte[] content = os.toByteArray();
            InputStream exportFileStream = new ByteArrayInputStream(content);
            String exportFileUrl = this.uploadFile(exportFileStream,fileName);
            if (StringUtils.isBlank(exportFileUrl)){
                return new MessageVO(PropertyErrorCodeEnum.PROJECT_EXPORT_FILE_SAVE_ERR.getErrorCode());
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), (Object) exportFileUrl);
        } catch (Exception e) {
            throw new DataAccessException("【物业-物业增值】导出欠费人员管理表单失败", e);
        }
    }

    /**
     * <desc>
     *      Ftp上传文件，返回Url.
     * </desc>
     *
     * @param inputStream 文件流
     * @param fileName 文件名称
     * @return 文件上传成功后会返回Url,否则返回空
     * @author wangzhi
     * @createDate 2019/05/22
     */
    private String uploadFile(InputStream inputStream, String fileName) throws IOException {
        String fileUrl = "";
        String fileType = StringHandlerUtil.copySubStr(fileName, fileName.lastIndexOf('.') + 1, fileName.length());
        UploadFileUtil.UploadFile uploadFileUtil = new UploadFileUtil().new UploadFile(
                FILE_FTP_HOST,
                FILE_FTP_USERNAME,
                FILE_FTP_PASSWORD,
                FILE_FTP_PORT,
                inputStream,
                fileType,
                FILE_ACCESS_URL,
                FileCatalogEnum.EXPORT_EXCEL_ZHANG_FILE.getType()
        );
        Map<String, Object> resultMap = UploadFileUtil.uploadFile(uploadFileUtil);
        Boolean returnCode = (Boolean)resultMap.get("returnCode");
        if (returnCode == false){
            return fileUrl;
        }
        fileUrl = resultMap.get("accessPath").toString();
        return fileUrl;
    }

}
